<template>
  <a-card style="width: 100%">
    <div class="header">
      <a-space class="left" direction="vertical">
        <Condition
          :condition="condition"
          :btns="['reset']"
          @search="onSearch"
          @reset="conditionReset"
        />
        <div class="title">共筛选出 {{ pagination.total }} 条数据</div>
      </a-space>
      <a-space class="right" direction="vertical">
        <a-input-search
          v-model:value="templateName"
          placeholder="请输入随访表单名称"
          style="width: 220px"
          @search="onSearch"
        />
        <!-- <a-input class="input" placeholder="请输入管理方案名称"></a-input> -->
        <a-button type="primary" @click="modalShow">新建随访表单</a-button>
      </a-space>
    </div>
    <div class="main">
      <a-table
        class="table"
        size="small"
        :loading="loading"
        :dataSource="List"
        :columns="columns"
        :pagination="pagination"
        @change="paginationChange"
        :sticky="{ offsetHeader: 0 }"
      >
        <template #bodyCell="{ column, text, index, record }">
          <template v-if="column.dataIndex === 'no'">
            {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
          </template>
          <template v-else-if="column.dataIndex === 'groupNames'">
            <a-space wrap>
              <a-tag type="parmary" v-for="(item, i) in record[column.dataIndex]" :key="i">{{
                item
              }}</a-tag>
            </a-space>
          </template>
          <template v-else-if="column.dataIndex === 'managePlanNames'">
            <a-space wrap>
              <a-tag type="success" v-for="(item, i) in record[column.dataIndex]" :key="i">
                {{ item }}</a-tag
              >
            </a-space>
          </template>
          <template v-else-if="column.dataIndex === 'createTime'">
            {{ record.createTime ? dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') : '' }}
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-button type="link" @click="modalShow2(record)">查看详情</a-button>
            <a-button
              type="link"
              :disabled="
                (record.managePlanNames && record.managePlanNames.length > 0) ||
                (record.groupNames && record.groupNames.length > 0)
                  ? true
                  : false
              "
              @click="delForm(record)"
              >删除表单</a-button
            >
          </template>
          <template v-else>
            {{ text }}
          </template>
        </template>
      </a-table>
    </div>
    <a-modal
      width="720px"
      :bodyStyle="store.userStore.bodyStyle"
      v-model:open="modal.open"
      :title="modal.title"
      ok-text="确认"
      cancel-text="取消"
      @ok="modalConfirm"
      :maskClosable="false"
    >
      <a-form
        class="modelForm"
        ref="modelForm"
        :colon="false"
        :model="formState"
        :label-col="{ style: { width: '80px' } }"
      >
        <a-form-item
          label="随访表单名称"
          :label-col="{ style: { width: '110px' } }"
          name="templateName"
          required
          :rules="{
            required: true,
            message: '随访表单名称不能为空',
            trigger: 'change'
          }"
        >
          <a-input
            style="width: 350px"
            v-model:value="formState.templateName"
            autocomplete="off"
            :maxlength="50"
            placeholder="请输入随访表单名称"
          />
        </a-form-item>
        <a-form-item>
          <a-row class="title">
            <a-col :span="24"> 随访表单内容 </a-col>
          </a-row>
        </a-form-item>
        <template v-for="(module, index) in formState.context" :key="index">
          <a-form-item
            :label="'模块' + numberToChinese(index + 1)"
            required
            :name="['context', index, 'name']"
            :rules="{
              required: true,
              message: '模块名不能为空',
              trigger: 'change'
            }"
          >
            <a-row>
              <a-col :span="24" class="row">
                <a-input
                  v-model:value="module.name"
                  autocomplete="off"
                  :maxlength="50"
                  placeholder="请输入模块名称"
                />
                <a-button v-if="index" type="link" danger @click="delTwo(index, formState.context)"
                  >删除模块</a-button
                >
              </a-col>
            </a-row>
          </a-form-item>
          <a-form-item
            v-for="(subitem, i) in module.list"
            :key="i"
            :name="['context', index, 'list', i]"
            :rules="{
              validator: subitem_check
            }"
            class="questionItem"
          >
            <a-form-item :label="'问题 ' + Number(i + 1)" :label-col="{ style: { width: '80px' } }">
              <a-row>
                <a-col :span="24" class="row" style="justify-content: space-between">
                  <a-select
                    v-model:value="subitem.type"
                    @change="subitemTypeChange($event, subitem)"
                    style="width: 120px"
                    :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                  >
                    <a-select-option
                      v-for="item in answertype"
                      :key="item.value"
                      :value="item.value"
                      >{{ item.label }}</a-select-option
                    >
                  </a-select>
                  <icon-font
                    v-if="i"
                    style="margin: 0 16px"
                    class="icon-del point"
                    type="icon-shanchu"
                    @click="del(i, module.list)"
                  />
                </a-col>
              </a-row>
            </a-form-item>
            <a-form-item>
              <a-row>
                <a-col :span="24" class="row">
                  <a-textarea
                    style="margin: 0 16px"
                    v-model:value="subitem.name"
                    placeholder="请输入问题描述"
                    :maxlength="500"
                    :rows="2"
                  />
                </a-col>
              </a-row>
            </a-form-item>
            <template v-if="subitem.type && subitem.type !== '输入'">
              <a-form-item>
                <draggable
                  class="drag"
                  :list="subitem.options"
                  :handle="'.icon-move'"
                  itemKey="id"
                  animation="300"
                  @end="moveOptions($event, subitem)"
                >
                  <template #item="{ element, index }">
                    <a-row class="item row" :gutter="[16, 0]">
                      <a-col>
                        <a-input
                          style="width: 240px"
                          v-model:value="element.value"
                          autocomplete="off"
                          :maxlength="50"
                          :disabled="element.disabled"
                          placeholder="请输入选项描述"
                        />
                      </a-col>
                      <a-col>
                        <icon-font class="icon-move" type="icon-yidong" />
                      </a-col>
                      <a-col class="row" style="flex: 1">
                        <a-radio
                          v-if="subitem.type.includes('+输入')"
                          :checked="element.input"
                          @change="elementChecked(index, subitem)"
                        >
                          添加输入框
                        </a-radio>
                      </a-col>
                      <a-col class="row">
                        <icon-font
                          v-if="index"
                          class="icon-del"
                          type="icon-shanchu"
                          @click="del(index, subitem.options)"
                        />
                        <icon-font
                          v-else
                          class="icon-plus"
                          type="icon-xinzeng"
                          @click="addOptions(subitem.options)"
                        />
                      </a-col>
                    </a-row>
                  </template>
                </draggable>
              </a-form-item>
            </template>
          </a-form-item>
          <a-form-item style="margin-top: -16px; background: #f7f8fa">
            <a-button type="link" :icon="h(PlusOutlined)" @click="addSubitem(module.list)"
              >新增问题</a-button
            >
          </a-form-item>
        </template>
        <a-form-item>
          <a-row class="title">
            <a-button class="add" :icon="h(PlusOutlined)" @click="addModule">添加模块</a-button>
          </a-row>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal
      width="720px"
      :bodyStyle="store.userStore.bodyStyle"
      v-model:open="modal2.open"
      :title="modal2.title"
      ok-text="确认"
      :maskClosable="false"
    >
      <a-form
        class="modelForm"
        ref="modelForm2"
        :model="formData"
        :colon="false"
        :label-col="{ style: { width: '110px' } }"
      >
        <a-form-item>
          <span class="title">{{ formData.templateName }}</span>
        </a-form-item>
        <a-form-item :label-col="{ style: { width: '110px' } }" label="已配置专病分组">
          <a-space wrap>
            <a-tag
              class="groupTag"
              type="parmary"
              v-for="(item, i) in formData.groupNames"
              :key="i"
              >{{ item }}</a-tag
            >
            <span class="empty-text" v-if="!formData.groupNames.length">暂无专病分组</span>
          </a-space>
        </a-form-item>
        <a-form-item :label-col="{ style: { width: '110px' } }" label="已配置管理方案">
          <a-space wrap>
            <a-tag type="success" v-for="(item, i) in formData.managePlanNames" :key="i">{{
              item
            }}</a-tag>
            <span class="empty-text" v-if="!formData.managePlanNames.length">暂无管理方案</span>
          </a-space>
        </a-form-item>
      </a-form>
      <t-form :formData="formData.context" :disabled="true" />
      <template #footer>
        <a-button
          key="back"
          :disabled="
            (formData.groupNames && formData.groupNames.length > 0) ||
            (formData.managePlanNames && formData.managePlanNames.length > 0)
              ? true
              : false
          "
          @click="modal2Cancel"
          >编辑</a-button
        >
        <a-button key="submit" type="primary" @click="modal2.open = false">确认</a-button>
      </template>
    </a-modal>
  </a-card>
</template>

<script lang="ts" setup name="管理方案">
import Condition from '@/components/Condition/index.vue'
import TForm from '@/components/TForm/index.vue'
import { h, createVNode } from 'vue'
import { PlusOutlined, ExclamationCircleFilled } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import draggable from 'vuedraggable'
import { numberToChinese, timeFilter } from '@/utils/tools'
import { getTemplateList, FollowFormAdd, FollowFormUpdate, FormDel } from '@/api/templateManage'
import { useDict } from './components/getDict'
import store from '@/store'
import _ from 'lodash'
import { getCreatorList } from '@/api/templateManage'
import dayjs from 'dayjs'
const templateType = 4
const templateName = ref('')

const { creatorList, groupList, planList } = useDict(templateType)

const answertype = [
  {
    label: '单选',
    value: '单选'
  },
  {
    label: '多选',
    value: '多选'
  },
  {
    label: '输入',
    value: '输入'
  },
  {
    label: '单选+输入',
    value: '单选+输入'
  },
  {
    label: '多选+输入',
    value: '多选+输入'
  }
]

const formState = reactive({
  id: '',
  groupNames: [],
  managePlanNames: [],
  templateName: '',
  templateType: templateType,
  context: [
    {
      name: '',
      list: [
        {
          name: '',
          type: '单选',
          options: [
            {
              id: 0,
              value: '',
              input: false,
              maxlength: 50
            }
          ]
        }
      ]
    }
  ]
})

const formState_reset = () => {
  Object.assign(formState, {
    id: '',
    groupNames: [],
    managePlanNames: [],
    templateName: '',
    templateType: templateType,
    context: [
      {
        name: '',
        list: [
          {
            name: '',
            type: '单选',
            options: [
              {
                id: 0,
                value: '',
                input: false,
                maxlength: 50
              }
            ]
          }
        ]
      }
    ]
  })
}

const condition = ref([
  {
    title: '创建者',
    dataIndex: 'creator',
    type: 'select',
    value: '',
    data: creatorList
  },
  {
    title: '已配置专病组',
    dataIndex: 'groupList',
    type: 'select',
    value: '',
    data: groupList
  },
  {
    title: '已配置管理方案',
    dataIndex: 'managePlanList',
    type: 'select',
    value: '',
    data: planList
  }
])

const conditionReset = () => {
  pagination.current = 1
  condition.value.map((v) => {
    v.value = ''
  })
  getList()
}

const pagination = reactive({
  current: 1,
  total: 0,
  pageSize: 10,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100']
})

const columns = ref([
  {
    title: '序号',
    dataIndex: 'no',
    key: 'no',
    align: 'left',
    width: '50px'
  },
  {
    title: '随访表单名称',
    dataIndex: 'templateName',
    key: 'templateName',
    align: 'left',
    minWidth: 100
  },
  {
    title: '已配置专病分组',
    dataIndex: 'groupNames',
    key: 'groupNames',
    align: 'left',
    minWidth: 200,
    ellipsis: true
  },
  {
    title: '已配置管理方案',
    dataIndex: 'managePlanNames',
    key: 'managePlanNames',
    align: 'left',
    minWidth: 200,
    ellipsis: true
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'left',
    width: '140px'
  },
  {
    title: '创建者',
    dataIndex: 'userName',
    key: 'userName',
    align: 'left',
    width: '80px'
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'left',
    width: '200px'
  }
])

const loading = ref(false)
const List = ref([])

const getList = () => {
  loading.value = true
  const { current, pageSize } = pagination
  const obj = condition.value.reduce((c, v) => {
    if (v.value || v.value === 0) {
      return Object.assign(c, { [v.dataIndex]: v.value })
    } else {
      return c
    }
  }, {})
  const params = {
    page: current,
    limit: pageSize,
    templateName: templateName.value,
    templateType: templateType,
    ...obj
  }
  getTemplateList(params)
    .then((res) => {
      loading.value = false
      if (res.data.total > 0 && !res.data.list.length) {
        pagination.current = pagination.current - 1
        getList()
      } else {
        pagination.total = res.data.total
        List.value = res.data.list
      }
    })
    .catch((e) => {
      loading.value = false
    })
}

const paginationChange = (p) => {
  Object.assign(pagination, p)
  getList()
}

const onSearch = () => {
  pagination.current = 1
  getList()
}

onMounted(() => {
  getList()
})

const modal = reactive({
  open: false,
  type: 'save',
  title: '新建随访表单'
})

const subitemTypeChange = (e, item) => {
  if (e === '输入' || !e) {
    item.options = []
  } else {
    item.options = [
      {
        id: 0,
        value: '',
        input: false,
        maxlength: 50
      }
    ]
  }
}

const moveOptions = (list, item) => {
  console.log('拖拽结束')
}

const del = (index, item) => {
  item.splice(index, 1)
}

const delTwo = (index, item) => {
  Modal.confirm({
    title: '删除',
    icon: createVNode(ExclamationCircleFilled, {
      style: {
        color: 'var(--color--danger)'
      }
    }),
    content: '确认是否删除',
    okText: '确定',
    okButtonProps: {
      danger: true,
      type: 'primary'
    },
    cancelText: '取消',
    onOk() {
      console.log('OK')
      item.splice(index, 1)
    },
    onCancel() {
      console.log('Cancel')
    }
  })
}

const addOptions = (item) => {
  const indexs = item.map((v) => {
    return v.id
  })
  let i = 0
  while (indexs.includes(i)) {
    i++
  }
  console.log(i)

  item.push({
    id: i,
    value: '',
    input: false,
    maxlength: 50
  })
}

const elementChecked = (value, subitem) => {
  subitem.options.map((v, index) => {
    if (value === index) {
      v.value = '其他'
      v.disabled = true
      v.input = true
    } else {
      if (v.disabled) {
        v.value = ''
      }
      v.disabled = false
      v.input = false
    }
  })
}

const addSubitem = (item) => {
  item.push({
    name: '',
    type: '单选',
    options: [
      {
        id: 0,
        value: '',
        input: false,
        maxlength: 50
      }
    ]
  })
}

const addModule = () => {
  formState.context.push({
    name: '',
    list: [
      {
        name: '',
        type: '单选',
        options: [
          {
            id: 0,
            value: '',
            input: false,
            maxlength: 50
          }
        ]
      }
    ]
  })
}

const subitem_check = async (_, value) => {
  if (value.type) {
    if (!value.name) {
      return Promise.reject('请输入问题描述')
    }
    if (value.type !== '输入') {
      const f = value.options.some((v) => {
        return v.value
      })
      if (!f) {
        return Promise.reject('请完善至少一个问题选项')
      }
      if (value.type.includes('+输入')) {
        const f2 = value.options.some((v) => {
          return v.input
        })
        if (!f2) {
          return Promise.reject('添加输入框需勾选')
        }
      }
    }
  } else {
    return Promise.reject('请选择问题类型')
  }
  return Promise.resolve()
}

const modelForm = ref(null)

const modalShow = () => {
  modelForm.value?.clearValidate()
  formState_reset()
  modal.title = '新建随访表单'
  modal.type = 'save'
  modal.open = true
}

const modalConfirm = () => {
  modelForm.value
    .validate()
    .then(() => {
      const context = _.cloneDeep(formState.context)
      context.map((v) => {
        v.list.map((u) => {
          if (u.type.includes('多')) {
            u['value'] = []
          } else {
            u['value'] = ''
          }
          u['inputText'] = ''
          if (u.type.includes('选')) {
            u.options.map((w) => {
              w['label'] = w.value
              w['disabled'] = false
            })
          }
        })
      })
      // 表单校验通过
      const params = { ...formState, context: JSON.stringify(context) }

      if (modal.type === 'save') {
        FollowFormAdd(params)
          .then((res) => {
            message.success('新建成功')
            // getList()
            modal.open = false
            useDictTwo()
            conditionReset()
            // location.reload()
          })
          .catch((e) => {
            console.log(e)
          })
      } else {
        FollowFormUpdate(params)
          .then((res) => {
            message.success('编辑成功')
            useDictTwo()
            getList()
            modal.open = false
          })
          .catch((e) => {
            console.log(e)
          })
      }
    })
    .catch((e) => {
      // 表单校验失败
      console.log(e)
      modelForm.value.scrollToField(e.errorFields[0].name, {
        behavior: 'smooth',
        block: 'center'
      })
    })
  // modal.open = false
}

const modal2 = reactive({
  title: '随访表单详情',
  open: false
})

const formData = ref()
const modelForm2 = ref(null)

const modalShow2 = (item) => {
  modelForm2.value?.clearValidate()
  const { id, groupNames, managePlanNames, templateName, templateType, context } = _.cloneDeep(item)
  const obj = {
    id,
    groupNames,
    managePlanNames,
    templateName,
    templateType,
    context: JSON.parse(context)
  }
  formData.value = obj
  modal2.open = true
}

const useDictTwo = () => {
  const obj = {
    label: '全部',
    value: ''
  }
  let creatorListTwo = []
  getCreatorList(4).then((res) => {
    if (res.data && res.data.length > 0) {
      creatorListTwo = res.data.map((v) => {
        return {
          label: v.userName,
          value: v.creator
        }
      })
    }
    creatorListTwo.unshift(obj)
    condition.value[0].data = creatorListTwo
  })
}
const delForm = (item) => {
  Modal.confirm({
    title: '删除',
    icon: createVNode(ExclamationCircleFilled, {
      style: {
        color: 'var(--color--danger)'
      }
    }),
    content: '确定删除该表单么',
    okText: '确定',
    okButtonProps: {
      danger: true,
      type: 'primary'
    },
    cancelText: '取消',
    onOk() {
      console.log('OK')
      FormDel(item.id).then(() => {
        message.success('删除成功')
        getList()
        useDictTwo()
      })
    },
    onCancel() {
      console.log('Cancel')
    }
  })
}

const modal2Cancel = () => {
  modelForm.value?.clearValidate()
  const obj = _.cloneDeep(formData.value)
  obj.context.map((w) => {
    w.list.map((v) => {
      if (v.type.includes('+输入')) {
        v.options.find((u) => {
          if (u.input) {
            u.disabled = true
            return true
          } else {
            return false
          }
        })
      }
    })
  })
  Object.assign(formState, obj)
  modal2.open = false
  modal.title = '编辑随访表单'
  modal.type = 'update'
  modal.open = true
}
</script>

<style lang="less" scoped>
@import './index.less';
.header {
  flex: 0 0 auto;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  .left {
    ::v-deep(.ant-space-item) {
      display: flex;
      flex-direction: row;
      align-items: center;
    }
    .title {
      font-size: 14px;
      font-family:
        PingFang SC,
        PingFang SC;
      font-weight: 400;
      color: #4e5969;
      line-height: 32px;
    }
  }
  .right {
    ::v-deep(.ant-space-item) {
      display: flex;
      flex-direction: row-reverse;
      align-items: center;
    }
  }
}
.main {
  flex: 1 1 auto;
  margin-top: 16px;
  overflow: hidden auto;
  :deep(.ant-table-wrapper) {
    .ant-table-cell {
      p {
        white-space: normal;
        margin-bottom: 0;
        .configuration {
          color: #3491fa;
          background: #e8f7ff;
          border-color: #3491fa;
          display: inline-block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 100%;
          margin-top: 10px;
          &:nth-child(1) {
            margin-top: 0;
          }
        }
        .success {
          color: #00b42a;
          background: #e8ffea;
          border-color: #00b42a;
          display: inline-block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 100%;
          margin-top: 10px;
          &:nth-child(1) {
            margin-top: 0;
          }
        }
        .groupTag {
          display: inline-block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 100%;
          margin-top: 10px;
          margin-right: 10px;
          &:nth-child(1) {
            margin-top: 0;
          }
        }
      }
    }
  }
}
.input {
  width: 210px !important;
}

.modelForm {
  .red {
    color: #f56667;
  }
  .ant-form-item {
    margin-bottom: 15px;
    &.questionItem {
      margin-bottom: 16px;
      padding-top: 8px;
      background: #f7f8fa;
    }
  }

  .title {
    width: 100%;
    height: 32px;
    font-family:
      PingFang SC,
      PingFang SC;
    font-weight: 500;
    font-size: 16px;
    font-family:
      PingFang SC,
      PingFang SC;
    font-weight: 500;
    color: #1d2129;
    line-height: 24px;
  }
  .add {
    width: 648px;
    height: 32px;
    font-size: 14px;
    font-family:
      PingFang SC,
      PingFang SC;
    font-weight: 400;
    color: #165dff;
    line-height: 22px;
    margin: 0 12px;
  }
  .icon-plus,
  .icon-del {
    font-size: 16px;
  }
  .icon-plus {
    color: #165dff;
  }
  .icon-del {
    color: #f53f3f;
  }
  .icon-move {
    color: #4e5969;
    font-size: 24px;
    line-height: 32px;
    cursor: move;
  }
}
.row {
  display: flex;
  flex-direction: row;
  align-items: center;
}
.drag {
  padding: 0 16px;
  .item:not(:first-child) {
    margin-top: 8px;
  }
}
.point {
  cursor: pointer;
}
</style>
